import java.util.Arrays;
import java.util.Random;

/**
 * Created with IntelliJ IDEA
 * Description:编写代码, 实现多线程数组求和.
 *     给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
 *     实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
 *     其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
 *     最终再汇总两个和, 进行相加
 *     记录程序的执行时间.
 * User:恋恋
 * Date:2022-11-26
 * Time:23:37
 */
class Count{
    int counter1;
    int counter2;

    public void addCounter1(int counter1) {
        this.counter1++;
    }

    public void addCounter2(int counter2) {
        this.counter2++;
    }
}
public class ThreadDemo2 {
    public static void main(String[] args) {

        long begin = System.currentTimeMillis();

        Count count = new Count();

        int[] arr = new int[1000_0000];

        Random random = new Random();//生成随机数的函数

        for (int i = 0; i < 1000_0000; i++) {

            arr[i] = random.nextInt(100) + 1;//生成[0，99]+1=[1,100]范围

        }

        Thread thread1 = new Thread(()->{

            for (int i = 0; i < arr.length; i+=2) {

                count.addCounter1(arr[i]);

            }
        });
        Thread thread2 = new Thread(()->{

            for (int i = 1; i < arr.length; i+=2) {

                count.addCounter2(arr[i]);

            }
        });
        //启动线程
        thread1.start();
        thread2.start();
        //关闭线程
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
      //  System.out.println(Arrays.toString(arr));
        System.out.println("偶数下标+奇数下标的总数="+(count.counter1+count.counter2));
        long end = System.currentTimeMillis();



        System.out.println("程序运行时间："+(end-begin));

    }
}
